workflow_actions = {
    save_form_workspace : function(elements){
        $("body").on("click",elements,function(){
        var form_type = $(this).attr("data-form-type");
                
                switch (form_type) {
                        case "workflow":
                                /*
                                    VALIDATE NODE SETTINGS ON WORKFLOW
                                */
                                var json_encode = $("body").data();
                                var json_node = json_encode['nodes'];
                                var json_line = json_encode['lines'];
                                var hasError = false;
                                //check if has nodes or lines
                                    if(json_haselement(json_node)== false || json_haselement(json_line)== false){
                                        hasError = true;
                                    }
                                //check if has correct node properties
                                for(var i in json_node){
                                    if(json_node[i]['type_rel']=="1"){
                                        //start
                                        var buttons = json_haselement(json_node[''+ i +'']['buttonStatus']);
                                        if(typeof json_node[''+ i +'']['buttonStatus'] == "undefined" || buttons == false){
                                            $("#"+json_node[''+ i +'']['node_data_id']).css("border-color","red");
                                            hasError = true;
                                        }
                                    }else if(json_node[i]['type_rel']=="2"){
                                        //process
                                        var buttons = json_haselement(json_node[''+ i +'']['buttonStatus']);
                                        if (typeof json_node[''+ i +'']['processorType'] == "undefined" || json_node[''+ i +'']['processorType'] == "" || json_node[''+ i +'']['processorType'] == "0" ||
                                        typeof json_node[''+ i +'']['processor'] == "undefined" || json_node[''+ i +'']['processor'] == "" || json_node[''+ i +'']['processor'] == "0" ||
                                        typeof json_node[''+ i +'']['node_text'] == "undefined" || json_node[''+ i +'']['node_text'] == "" ||
                                        typeof json_node[''+ i +'']['status'] == "undefined" || json_node[''+ i +'']['status'] == "" /*||
                                        typeof json_node[''+ i +'']['buttonStatus'] == "undefined" || buttons == false*/){
                                            hasError = true;
                                            $("#"+json_node[''+ i +'']['node_data_id']).css("border-color","red");
                                        }
                                    }else if(json_node[i]['type_rel']=="3"){
                                        //condition
                                        var condition_return =  json_haselement(json_node[''+ i +'']['condition_return']);
                                        if(typeof json_node[''+ i +'']['field'] == "undefined" || json_node[''+ i +'']['field'] == "" ||
                                        typeof json_node[''+ i +'']['operator'] == "undefined" || json_node[''+ i +'']['operator'] == "" ||
                                        typeof json_node[''+ i +'']['field_value'] == "undefined" ||
                                        condition_return == false){
                                            hasError = true;
                                            $("#"+json_node[''+ i +'']['node_data_id']).css("border-color","red");
                                        }
                                        
                                    }else if(json_node[i]['type_rel']=="4"){
                                        //end
                                        if(typeof json_node[''+ i +'']['status'] == "undefined" || json_node[''+ i +'']['status'] == ""){
                                            hasError = true;
                                            $("#"+json_node[''+ i +'']['node_data_id']).css("border-color","red");
                                        }
                                    }
                                }
                                if(hasError==true){
                                   showNotification({
                                         message: "You have an error on your node settings",
                                         type: "error",
                                         autoClose: true,
                                         duration: 3
                                        });
                                }else{
                                    /*WORKFLOW SAVE*/
                                    var form_id = $("#form_id").val();
                                    json_encode['title'] = $("#workspace_title").val();
                                    json_encode['description'] = $("#workspace_description").val();
                                    json_encode['form_id'] = form_id;
                                    json_encode['width'] = $(".form_size_width").val();
                                    json_encode['height'] = $(".form_size_height").val();
                                    if(json_encode['title']==""){
                                        showNotification({
                                            message: "Please fill out the required fields",
                                            type: "error",
                                            autoClose: true,
                                            duration: 3
                                        });
                                        return;
                                    }
                                    //for (var i in json_encode['nodes']) {
                                    //            json_encode['nodes'][i]['node_onDrop'] = ""+json_encode['nodes'][i]['node_onDrop'];
                                    //}
                                    // = JSON.stringify(json_encode);
                                    json_encode = JSON.stringify(json_encode, function(key, val) {
                                                if (typeof val === 'function') {
                                                  return val + ''; // implicitly `toString` it
                                                }
                                                return val;
                                    })
                                    ui.block();
                                    $.post("/ajax/workflow",{action:"saveWorkflow",json_encode:json_encode},function(data){
                                        //console.log(data)
                                        showNotification({
                                         message: data,
                                         type: "success",
                                         autoClose: true,
                                         duration: 3
                                        });
                                        $("#popup_overlay,#popup_container").remove();
                                        ui.unblock();
                                    })
                                }
                        break;
                }
            });
            
    },
    save_node_settings: function(callback){
        var self = this;
            
            $(".settings-to-json").click(function(e){
                var type = $(this).attr("object_type");
                var node_data_id =  $(this).attr("node-data-id");
                var json_nodes = $("body").data();
                var json_nodes_var = json_nodes['nodes'];
                var close_dialog = true;
                if (type == "organizational_chart") {
                    /*ORGCHART*/
                    //values from dialog
                    var orgchart_dept_name = $("#orgchart-dept-name").val();
                    var orgchart_node_color = $("#orgchart-node-color").val();
                    var orgchart_user_head = self.head_id;
                    var orgchart_dept_assistant = self.assistantHead_id;
                    var orgchart_dept_members = self.members_id;
                    var workflow_status = $(".head_user:checked").closest(".orgchart_user_wrap").find(".avatar-oc").html();
                    var head_name = $(".head_user:checked").closest(".orgchart_user_wrap").find(".limit-text-wf").text();
                    //set value on json['nodes']
                    json_nodes_var[''+ node_data_id +'']['node_text'] = orgchart_dept_name;
                    json_nodes_var[''+ node_data_id +'']['node_color'] = orgchart_node_color;
                    json_nodes_var[''+ node_data_id +'']['orgchart_user_head'] = orgchart_user_head;
                    json_nodes_var[''+ node_data_id +'']['orgchart_dept_assistant'] = orgchart_dept_assistant;
                    json_nodes_var[''+ node_data_id +'']['orgchart_dept_members'] = orgchart_dept_members
                    json_nodes_var[''+ node_data_id +'']['status'] = workflow_status;

                      
                    if($("#"+node_data_id).hasClass("node-drag-wrapper")){
                        $("#" + node_data_id).find(".node-avatar-wrapper").html(workflow_status);
                        $("#" + node_data_id).find(".node-avatar-wrapper").find("img").attr({
                            "width" : "35",
                            "height" : ""
                        })
                        workflow_status = $("#" + node_data_id).find(".node-avatar-wrapper").html();
                        json_nodes_var[''+ node_data_id +'']['status'] = workflow_status;
                        json_nodes_var[''+ node_data_id +'']['head_name'] = head_name;
                        $("#node_status_" + node_data_id).html(head_name);
                        $("#"+node_data_id).find(".node-bg-color").css({
                            "background-color":orgchart_node_color
                        })
                    }else{
                        $("#node_status_" + node_data_id).html(workflow_status);
                        $("#node_process_" + node_data_id).css("background-color",orgchart_node_color);
                    }

                    // Change the properties of node
                    $("#node_title_" + node_data_id).html(orgchart_dept_name);
                    
                    
                    $(".node-other-text").find("img").css({
                        "z-index": "2",
                        "position": "relative"
                    })
                    $(".node-other-text").find("img").attr({
                        "width":"30",
                        "height":"30"
                    })
                            
                }else if(type == "workflow_chart-processor"){
                    /*WORKFLOW PROCESSSOR*/
                    //values from dialog
                    var workflow_processor_type = $("#workflow-processor-type").val();
                    var workflow_processor = $("#workflow-processor").val();
                    var workflow_processor_text = $("#workflow-processor :selected").text();
                    var workflow_status = $("#workflow-status").val();
                    var workflow_field_enabled = array_store(".fieldEnabled","checkbox");
                    var workflow_field_required = array_store(".fieldRequired","checkbox");
                    var workflow_field_hidden = array_store(".fieldHiddenValue","checkbox");
                    var workflow_default_action = $("#workflow-default-action").val() 
                    //set value on json['nodes']
                    if(workflow_processor_type!="0" && workflow_processor!="0" && workflow_status!=""){
                        json_nodes_var[''+ node_data_id +'']['processorType'] = workflow_processor_type;
                        json_nodes_var[''+ node_data_id +'']['processor'] = workflow_processor;
                        json_nodes_var[''+ node_data_id +'']['node_text'] = workflow_processor_text;
                        json_nodes_var[''+ node_data_id +'']['status'] = workflow_status;
                        json_nodes_var[''+ node_data_id +'']['fieldEnabled'] = workflow_field_enabled;
                        json_nodes_var[''+ node_data_id +'']['fieldRequired'] = workflow_field_required;
                        json_nodes_var[''+ node_data_id +'']['fieldHiddenValue'] = workflow_field_hidden;
                        json_nodes_var[''+ node_data_id +'']['workflow-default-action'] = workflow_default_action;
                        //
                    
                        if($("#"+node_data_id).hasClass("node-drag-wrapper")){
                            $("#"+node_data_id).find(".node-dept-wrapper").text(workflow_processor_text);
                            $("#"+node_data_id).find(".node-name-wrapper").text(workflow_status);
                        }else{
                            // Change Node Status on the selected node
                            $("#" + node_data_id).find(".node-title").html(workflow_processor_text);
                            $("#node_status_" + node_data_id).html(workflow_status);
                        }
                    }else{
                        close_dialog = false;
                        // alert("Please complete all required fields")
                        showNotification({
                             message: "Please complete all required fields",
                             type: "error",
                             autoClose: true,
                             duration: 3
                        });
                    }
                }else if (type == "workflow_chart-start") {
                            /*WORKFLOW START*/

                            //values from dialog
                            var workflow_field_enabled = array_store(".fieldEnabled","checkbox");
                            var workflow_field_required = array_store(".fieldRequired","checkbox");
                            var workflow_field_hidden = array_store(".fieldHiddenValue","checkbox"); 
                            //set value on json['nodes']
                            json_nodes_var[''+ node_data_id +'']['fieldEnabled'] = workflow_field_enabled;
                            json_nodes_var[''+ node_data_id +'']['fieldRequired'] = workflow_field_required;
                            json_nodes_var[''+ node_data_id +'']['fieldHiddenValue'] = workflow_field_hidden;
                            
                }else if (type == "workflow_chart-condition") {
                    /*WORKFLOW CONDITION*/
                    //values from dialog
                    var wokflow_condition_fields = $(".wokflow_condition-fields").val();
                    var wokflow_condition_operator = $(".wokflow_condition-operator").val();
                    var wokflow_condition_value = $("#wokflow_condition-value").val();
                    var condition_status = wokflow_condition_fields+" "+wokflow_condition_operator+" "+wokflow_condition_value;
                    //set value on json['nodes']
                    json_nodes_var[''+ node_data_id +'']['field'] = wokflow_condition_fields;
                    json_nodes_var[''+ node_data_id +'']['operator'] = wokflow_condition_operator;
                    json_nodes_var[''+ node_data_id +'']['field_value'] = wokflow_condition_value;
                    json_nodes_var[''+ node_data_id +'']['status'] = condition_status;

                    if($("#"+node_data_id).hasClass("node-drag-wrapper")){
                        $("#" + node_data_id).find(".node-name-wrapper").html(condition_status);
                    }else{
                        $("#node_status_" + node_data_id).html(condition_status);
                    }
                            
                }else if (type == "workflow_chart_buttons") {
                    /*WORKFLOW SET BUTTONS*/
                    var workflow_button = $(".workflow-buttons").val();
                    var workflow_require_comment = $("#wokflow_button-require").prop("checked");
                    var wokflow_button_line_color = $("#wokflow_button-line-color").val();
                    var child_id = $("#wokflow_button-action").attr("child_id");
                    var parent_id = $("#wokflow_button-action").attr("parent_id");
                    var line_class = parent_id+"_"+child_id;
                    if (workflow_button==0) {
                                close_dialog = false;
                                showNotification({
                                     message: "Please select button",
                                     type: "error",
                                     autoClose: true,
                                     duration: 3
                                });
                    }else{
                                //set value on json['nodes']
                                json_nodes_var[''+ node_data_id +'']['buttonStatus'] = (json_nodes_var[''+ node_data_id +'']['buttonStatus']  == null)?{}:json_nodes_var[''+ node_data_id +'']['buttonStatus'];
                                var buttons_json = {};
                                buttons_json['button_name'] = workflow_button;
                                buttons_json['child_id'] = child_id;
                                buttons_json['parent_id'] = parent_id;
                                buttons_json['require_comment'] = workflow_require_comment;
                                buttons_json['wokflow_button_line_color'] = wokflow_button_line_color;
                                json_nodes_var[''+ node_data_id +'']['buttonStatus'][''+ workflow_button +''] = buttons_json;

                                
                                //callback
                                callback(wokflow_button_line_color,workflow_button);     

                                //append button name
                                customTextLine(line_class,workflow_button);

                    }
                    
                }else if (type == "workflow_chart_condition-line") {
                    var wokflow_condition_line_color = $("#wokflow_condition-line-color").val();
                    var wokflow_condition_return_boolean = $(".wokflow_condition-return-boolean:checked").val();
                    var child_id = $("#wokflow_condition-action").attr("child_id");
                    var parent_id = $("#wokflow_condition-action").attr("parent_id");
                    var line_class = parent_id+"_"+child_id;
                    if (typeof wokflow_condition_return_boolean =="undefined") {
                                //code
                                close_dialog = false;
                                // alert("select return");
                                showNotification({
                                     message: "Please select return value",
                                     type: "error",
                                     autoClose: true,
                                     duration: 3
                                });
                    }else{
                                //var wokflow_condition_line_color = $("#wokflow_condition-line-color").val();
                                json_nodes_var[''+ node_data_id +'']['condition_return'] = (json_nodes_var[''+ node_data_id +'']['condition_return']  == undefined)?{}:json_nodes_var[''+ node_data_id +'']['condition_return'];
                                var buttons_json = {};
                                buttons_json['child_id'] = child_id;
                                buttons_json['parent_id'] = parent_id;
                                buttons_json['wokflow_condition_return_boolean'] = wokflow_condition_return_boolean;
                                json_nodes_var[''+ node_data_id +'']['condition_return'][''+ wokflow_condition_return_boolean +''] = buttons_json;
                                

                                callback(wokflow_condition_line_color,wokflow_condition_return_boolean);
                                customTextLine(line_class,wokflow_condition_return_boolean);
                    }
                            
                }else if (type == "workflow_chart-end") {
                  var workflow_end_status  = $("#workflow_end-status").val();
                  if(workflow_end_status!=""){
                    json_nodes_var[''+ node_data_id +'']['status'] = workflow_end_status;
                  }else{
                    close_dialog = false;
                    // alert("Please complete all required fields")
                    showNotification({
                         message: "Please complete all required fields",
                         type: "success",
                         autoClose: true,
                         duration: 3
                    });
                  }
                  // Change Node Status on the selected node
                  if($("#"+node_data_id).hasClass("node-drag-wrapper")){
                    $("#" + node_data_id).find(".node-circle-status").text(workflow_end_status); 
                  }else{
                    $("#node_status_" + node_data_id).html(workflow_end_status); 
                  }
                  
                   
                }else if(type == "workflow_chart-email"){
                    var workflow_email = {};
                    var workflow_sms = {};
                    //start to
                    var email_to = {};
                    var requestor_to = $(".email-to").find(".email-requestor").prop("checked");
                    var processor_to = $(".email-to").find(".email-processor").prop("checked");
                    var users_to = self.setCheckedToJson(".email-to");

                    email_to = {
                        "requestor" : requestor_to,
                        "processor" : processor_to,
                    };
                    email_to = $.extend(users_to,email_to);
                    //end to
                    //start cc
                    var email_cc = {};

                    var requestor_cc = $(".email-cc").find(".email-requestor").prop("checked");
                    var processor_cc = $(".email-cc").find(".email-processor").prop("checked");
                    var users_cc = self.setCheckedToJson(".email-cc");

                    email_cc = {
                        "requestor" : requestor_cc,
                        "processor" : processor_cc,
                    };
                    email_cc = $.extend(users_cc,email_cc);

                    //end cc

                    //start bcc
                    var email_bcc = {};

                    var requestor_bcc = $(".email-bcc").find(".email-requestor").prop("checked");
                    var processor_bcc = $(".email-bcc").find(".email-processor").prop("checked");
                    var users_bcc = self.setCheckedToJson(".email-bcc");

                    email_bcc = {
                        "requestor" : requestor_bcc,
                        "processor" : processor_bcc,
                    };
                    email_bcc = $.extend(users_bcc,email_bcc);
                    //end bcc

                    //title and message

                    //push to json
                    var email_title = $("#workflow-email-title").val();
                    var title_type = $(".workflow-email-title-type:checked").val();
                    var email_message = $("#workflow-email-message").val();
                    var email_message_type = $(".workflow-email-message-type:checked").val();

                    workflow_email = {
                        "email_recpient" : email_to,
                        "email_cc"  : email_cc,
                        "email_bcc" : email_bcc,
                        "title"     : email_title,
                        "email-title-type": title_type,
                        "message"   : email_message,
                        "email-message-type" :email_message_type

                    };
                    var requestor_sms = $(".sms-users").find(".sms-requestor").prop("checked");
                    var processor_sms = $(".sms-users").find(".sms-processor").prop("checked");
                    var users_sms = self.setCheckedToJson(".sms-users");
                    var sms_contact = $("#workflow-sms-contact").val();
                    var sms_message = $("#workflow-sms-message").val();
                    var sms_message_type = $(".workflow-sms-message-type:checked").val();
                    workflow_sms = {
                        "requestor" : requestor_sms,
                        "processor" : processor_sms,
                        "contact"   : sms_contact,
                        "message"   : sms_message,
                        "message-type" : sms_message_type
                    };
                    workflow_sms = $.extend(users_sms,workflow_sms);

                    json_nodes_var[''+ node_data_id +'']['workflow_email'] = workflow_email;
                    json_nodes_var[''+ node_data_id +'']['workflow_sms'] = workflow_sms;
                // }else if(type=="workflow_chart-fields-trigger"){
                //     //values from dialog
                //     //set value on json['nodes']
                //     var workflow_trigger_action = $(".workflow-trigger-action:checked").val()
                //     if(workflow_trigger_action=="Create"){
                //         json_nodes_var[''+ node_data_id +'']['workflow-form-trigger'] = $("#workflow-form-trigger").val();
                //         json_nodes_var[''+ node_data_id +'']['workflow-reference-fields-update'] = $(".workflow-reference-fields-update").val();
                //     }else{
                        
                //         json_nodes_var[''+ node_data_id +'']['workflow-trigger-fields-update'] = $("#workflow-trigger-fields-update").val();
                //         json_nodes_var[''+ node_data_id +'']['workflow-trigger-fields-filter'] = $("#workflow-trigger-fields-filter").val();
                //         json_nodes_var[''+ node_data_id +'']['workflow-trigger-operator'] = $("#workflow-trigger-operator").val();
                //     }
                //     json_nodes_var[''+ node_data_id +'']['workflow-trigger-action'] = workflow_trigger_action;
                // }
                //multi
                }else if(type=="workflow_chart-fields-trigger"){
                    var json_field_trigger = [];
                    $(".trigger-container-fields").each(function(){
                        if($(this).find(".workflow-trigger-action-class:checked").val()=="Create" || $(this).find(".workflow-trigger-action-class:checked").val()=="Update Response"){
                            if($(this).find(".workflow-form-trigger").val()!=0){
                                var fields_formula = [];
                                $(this).find(".fields_formula_row").each(function(){
                                    fields_formula.push({
                                        "workflow-field-update" : $(this).find(".workflow-reference-fields-update").val(),
                                        "workflow-field-id" : $(this).find(".workflow-reference-fields-update").attr("id"),
                                        "workflow-field-formula" : $(this).find(".workflow-reference-fields-formula").val(),
                                    })
                                })
                                json_field_trigger.push({
                                    "workflow-trigger-action":$(this).find(".workflow-trigger-action-class:checked").val(),
                                    "workflow-form-trigger":$(this).find(".workflow-form-trigger").val(),
                                    "workflow-field_formula":fields_formula,
                                    "workflow-ref-field" : $(this).find(".workflow-ref-field").val()
                                });
                                json_nodes_var[''+ node_data_id +'']['workflow-trigger'] = json_field_trigger;
                            }
                        }else{
                            json_field_trigger.push({
                                "workflow-trigger-action":$(this).find(".workflow-trigger-action-class:checked").val(),
                                "workflow-trigger-fields-update":$(this).find(".workflow-trigger-fields-update").val(),
                                "workflow-trigger-fields-filter":$(this).find(".workflow-trigger-fields-filter").val(),
                                "workflow-trigger-operator":$(this).find(".workflow-trigger-operator").val()
                            });
                            json_nodes_var[''+ node_data_id +'']['workflow-trigger'] = json_field_trigger;
                        }
                    })

                    
                }
                
                if(close_dialog==true){
                            //set json on body
                            $("body").data(json_nodes);
                            console.log($("body").data())
                            //remove dialog
                            $("#popup_overlay,#popup_container").remove();
                            //callback
                }
                        
            });
    },
    head_id : [],
    assistantHead_id : [],
    members_id : [],
    setMembers : function(){
        var self = this;
        self.head_id = array_store(".head_user","checkbox");
        self.assistantHead_id = array_store(".asst_head_user","checkbox");
        self.members_id = array_store(".member_user","checkbox");
        

    },
    setMembersFunction : function(){
        var self = this;
        var index_arr = "";
        $("body").on("click",".member_user",function(){
            var value = $(this).val();
            if($(this).prop("checked")){
                self.members_id.push(value);
            }else{
                index_arr = self.members_id.indexOf(value);
                self.members_id.splice(index_arr,1);
            }
            console.log(self.members_id)
        })
        $("body").on("click",".head_user",function(){
            var value = $(this).val();
            self.head_id = [];
            self.head_id.push(value);
        })
        $("body").on("click",".asst_head_user",function(){
            var value = $(this).val();
            self.assistantHead_id = [];
            self.assistantHead_id.push(value);
        })
    },
    setCheckedToJson : function(cont){
        var json = {};
        var departments = [];
        var positions = [];
        var users = [];
        //for deoartments
        $(cont).find(".departments").each(function(){
            if($(this).prop("checked")){
                departments.push($(this).val());
            }
        })
        //for positions
        $(cont).find(".positions").each(function(){
            if($(this).prop("checked")){
                positions.push($(this).val());
            }
        })
        //for users
        $(cont).find(".users").each(function(){
            if($(this).prop("checked")){
                users.push($(this).val());
            }
        })
        json = {
            "departments" : departments,
            "positions" : positions,
            "users" : users
        }
        return json;
    },
    save_node_mail : function(node_data_id){
        var json = $("body").data();
        ui.block();
        jDialog(object_properties_node("workflow_chart-email",node_data_id,""), "","700", "", "", function(){});
        converBreakLineTextbox("#workflow-sms-message");
        converBreakLineTextbox("#workflow-email-message");
        limitText(".limit-text-wf",20); // set limit of text in the name   

        $(".tip").tooltip(); 
        $( "#accordion" ).accordion({
            heightStyle: "fill",
            activate: function( event, ui ) {
                // $('.content-dialog-scroll').perfectScrollbar()
                // $(".ps-scrollbar-x").hide();    
                //alert(1)
                // $('.content-dialog-scroll').perfectScrollbar('destroy');
                // $('.content-dialog-scroll').perfectScrollbar()
                // $(".ps-scrollbar-x").hide();    
                $('.content-dialog-scroll').perfectScrollbar('update');
            }
        });
        // $( "#accordion-container" ).accordion({
        //     heightStyle: "fill",
        //     activate: function( event, ui ) {
        //         // $('.content-dialog-scroll').perfectScrollbar()
        //         // $(".ps-scrollbar-x").hide();    
        //         //alert(1)
        //         // $('.content-dialog-scroll').perfectScrollbar('destroy');
        //         // $('.content-dialog-scroll').perfectScrollbar()
        //         // $(".ps-scrollbar-x").hide();    
        //         $('.content-dialog-scroll').perfectScrollbar('update');
        //         $('.content-dialog-scroll-container').perfectScrollbar('update');
        //     }
        // });
        $( "#accordion-container" ).tabs({
            activate : function(){
                $('.content-dialog-scroll').perfectScrollbar('update');
                $('.content-dialog-scroll-container').perfectScrollbar('update');
            }
        })
        $(".ui-accordion-content").css({
            "height":"auto",
            "font-size":"11px",
        })
        this.save_node_settings()
        //object_properties_node(object_type,parent_id,child_id)

        //set json to fields
        var json_nodes = $("body").data();
        var json_nodes_var = json_nodes['nodes'];
        var workflow_email  = if_undefinded(json_nodes_var[''+ node_data_id +'']['workflow_email'],"");
        var workflow_sms  = if_undefinded(json_nodes_var[''+ node_data_id +'']['workflow_sms'],"");

        if(workflow_email){
            //to
            var to = workflow_email['email_recpient'];
            $(".email-to").find(".email-requestor").prop("checked",to['requestor']);
            $(".email-to").find(".email-processor").prop("checked",to['processor']);
            RequestPivacy.setCheckAllChecked($(".fp-user-to"));
            //cc
            var cc = workflow_email['email_cc'];
            $(".email-cc").find(".email-requestor").prop("checked",cc['requestor']);
            $(".email-cc").find(".email-processor").prop("checked",cc['processor']);
            RequestPivacy.setCheckAllChecked($(".fp-user-cc"));
            //bcc
            var bcc = workflow_email['email_bcc'];
            $(".email-bcc").find(".email-requestor").prop("checked",bcc['requestor']);
            $(".email-bcc").find(".email-processor").prop("checked",bcc['processor']);            
            RequestPivacy.setCheckAllChecked($(".fp-user-bcc"));
            
        }

        if(workflow_sms){
            //sms
            $(".sms-users").find(".sms-requestor").prop("checked",workflow_sms['requestor']);
            $(".sms-users").find(".sms-processor").prop("checked",workflow_sms['processor']);         
            RequestPivacy.setCheckAllChecked($(".fp-user-sms"));
        }
        ui.unblock();
    },
    // field_trigger_settings : function(node_data_id){
    //     var json = $("body").data();
    //     var json_nodes_var = json['nodes'];
    //     jDialog(object_properties_node("workflow_chart-fields-trigger",node_data_id,"field-trigger"), "","650", "200", "", function(){});


    //     var workflow_trigger_action = if_undefinded(json_nodes_var[''+ node_data_id +'']['workflow-trigger-action'],"");
    //     var workflow_trigger_fields_update = if_undefinded(json_nodes_var[''+ node_data_id +'']['workflow-trigger-fields-update'],"");
    //     var workflow_trigger_fields_filter = if_undefinded(json_nodes_var[''+ node_data_id +'']['workflow-trigger-fields-filter'],"");
    //     var workflow_trigger_operator = if_undefinded(json_nodes_var[''+ node_data_id +'']['workflow-trigger-operator'],"");

    //     var workflow_form_trigger = if_undefinded(json_nodes_var[''+ node_data_id +'']['workflow-form-trigger'],"");
    //     var workflow_reference_fields_update = if_undefinded(json_nodes_var[''+ node_data_id +'']['workflow-reference-fields-update'],"");
    //     // setting up values
        
    //     if(workflow_trigger_action){
    //         $(".workflow-trigger-action[value='"+ workflow_trigger_action +"']").attr("checked","checked");
    //         if(workflow_trigger_action=="Create"){
    //             $(".forUpdateTrgger").addClass("display")
    //             $(".forCreateTrgger").removeClass("display")
    //             if(workflow_form_trigger){
    //                 $("#workflow-form-trigger").val(workflow_form_trigger)
    //             }
    //             getFormFields(workflow_form_trigger,workflow_reference_fields_update)
    //         }else{
    //             $(".forCreateTrgger").addClass("display")
    //             $(".forUpdateTrgger").removeClass("display")

    //             if(workflow_trigger_fields_filter){
    //                 $("#workflow-trigger-fields-filter").val(workflow_trigger_fields_filter)
    //             }
    //             if(workflow_trigger_fields_update){
    //                 $("#workflow-trigger-fields-update").val(workflow_trigger_fields_update)
    //             }
    //             if(workflow_trigger_operator){
    //                 $("#workflow-trigger-operator").val(workflow_trigger_operator)
    //             }
    //         }
    //     }
    //     //call function for saving
    //     this.save_node_settings()
    //     this.updateTrigger();
    //     this.updateFieldReference();
    // },
    updateTrigger: function(){

        // $(".workflow-trigger-action").change(function(){
        //     var value = $(this).val();
        //     alert(value)
        //     if(value=="Create"){
        //         alert(1)
        //         $(this).closest(".trigger-container-fields").find(".forUpdateTrgger").addClass("display")
        //         $(this).closest(".trigger-container-fields").find(".forCreateTrgger").removeClass("display")
        //     }else{
        //         $(this).closest(".trigger-container-fields").find(".forCreateTrgger").addClass("display")
        //         $(this).closest(".trigger-container-fields").find(".forUpdateTrgger").removeClass("display")
        //     }
        // })

        //multi
        $(".workflow-trigger-action-class").change(function(){
            var value = $(this).val();

            if(value=="Create"){
                $(this).closest(".trigger-container-fields").find(".forUpdateTrgger").addClass("display")
                $(this).closest(".trigger-container-fields").find(".forCreateTrgger").removeClass("display")
                $(this).closest(".trigger-container-fields").find(".fields_formula_row").css("display","block")
                 $(this).closest(".trigger-container-fields").find(".forUpdateResponse").addClass("display")
            }else if(value=="Update Response"){
                $(this).closest(".trigger-container-fields").find(".forUpdateTrgger").addClass("display")
                $(this).closest(".trigger-container-fields").find(".forCreateTrgger").removeClass("display")
                $(this).closest(".trigger-container-fields").find(".fields_formula_row").css("display","block")
                $(this).closest(".trigger-container-fields").find(".forUpdateResponse").removeClass("display")
            }else{
                $(this).closest(".trigger-container-fields").find(".forCreateTrgger").addClass("display")
                $(this).closest(".trigger-container-fields").find(".forUpdateTrgger").removeClass("display")
                $(this).closest(".trigger-container-fields").find(".forUpdateResponse").addClass("display")
            }
        })
    },
    updateFieldReference: function(){
        // $("#workflow-form-trigger").change(function(){
        //     getFormFields($(this).val(),0);
        // })
        
        //multi
        $(".workflow-form-trigger").change(function(){
            getFormFields($(this),$(this).val(),0);
        })
    },
    //multi
    field_trigger_settings : function(node_data_id){
        var json = $("body").data();
        var json_nodes_var = json['nodes'];
        ui.block()
        jDialog(object_properties_node("workflow_chart-fields-trigger",node_data_id,"field-trigger"), "","700", "", "-20", function(){});
        $("#content-dialog-scroll").perfectScrollbar();

        var workflow_trigger = if_undefinded(json_nodes_var[''+ node_data_id +'']['workflow-trigger'],"");
        var workflow_trigger2 = if_undefinded(json_nodes_var[''+ node_data_id +'']['workflow-trigger'],"");

        if(workflow_trigger){
            // var k = triggerHtml(workflow_trigger);
            // $(".content-dialog").html(k)
            // for(var i in workflow_trigger){
            //     getFormFields($("#workflow-form-trigger_"+i),workflow_trigger[i]['workflow-form-trigger'],workflow_trigger[i]['workflow-reference-fields-update']);
            // }   
            var ret = "";
            for(var i in workflow_trigger){
                ret += this.trigger_html(i,workflow_trigger[i]);
            }
            $(".content-dialog").html(ret);
            ui.unblock()
            var field_formula = "";
            for(var i in workflow_trigger){
                var frm_trigger = $(".trigger-container-fields_"+[i]).find(".workflow-form-trigger");
                getFormFields(frm_trigger,frm_trigger.val(),"",function(){
                    if(i==workflow_trigger.length-1){ //perform at the last loop
                        for(var l in workflow_trigger2){
                            field_formula = workflow_trigger2[l]['workflow-field_formula'];
                            for(var kk in field_formula){
                                // console.log(field_formula[kk])
                                $("#"+field_formula[kk]['workflow-field-id']).val(field_formula[kk]['workflow-field-update'])
                            }
                        }
                        $(".fields_formula_row").show();
                        ui.unblock()
                    }
                });

                // $("#"+field_formula[j]['workflow-field-id']).val(field_formula[j]['workflow-field-update'])
            }
            $("#content-dialog-scroll").perfectScrollbar("update");

        }else{
            $(".fields_formula_row").show();
            ui.unblock()
        }
        //call function for saving
        this.save_node_settings()
        this.updateTrigger();
        this.updateFieldReference();
        
    },field_trigger_custom : function(){
        var self = this;
        var ctr_triggerhtml = 0;
        var ctr_fields_formula = 0;
        $("body").on("click",".addtrigger",function(){
            ctr_triggerhtml = $(".trigger-container-fields").length;
            var htmlStr = self.trigger_html(ctr_triggerhtml++,"");
            
            $(this).closest(".trigger-container-fields").after(htmlStr)
            $(".fields_formula_row").show();
            $("#content-dialog-scroll").perfectScrollbar("update");
            self.updateTrigger();
            self.updateFieldReference();
        })
        $("body").on("click",".minusTrigger",function(){
            $(this).closest(".trigger-container-fields").remove()
            $("#content-dialog-scroll").perfectScrollbar("update");
        })
        $("body").on("click",".addFieldtrigger",function(){
            var index_fieldTrigger = $(this).closest(".trigger-container-fields").index();
            ctr_fields_formula = $(this).closest(".trigger-container-fields").find(".workflow-reference-fields-update").length;
            var htmlStr = self.fields_formula(index_fieldTrigger,"",ctr_fields_formula++);
            $(this).closest(".fields_formula").append(htmlStr);
            $(".fields_formula_row").fadeIn();
            $("#content-dialog-scroll").perfectScrollbar("update");
            //  $(".workflow-form-trigger").change(function(){
                
            // })
            var workflow_form_trigger = $(this).closest(".trigger-container-fields").find(".workflow-form-trigger");
            getFormFields(workflow_form_trigger,workflow_form_trigger.val(),"null");
        })
        $("body").on("click",".minusFieldTrigger",function(){
            $(this).closest(".fields_formula_row").fadeOut(function(){
                $(this).remove()
            });
            $("#content-dialog-scroll").perfectScrollbar("update");
        })
    },
    trigger_html : function(ctr,data){
        var form_fields = $(".form_fields").val();
        var forms = $(".company_forms").text();
        forms = JSON.parse(forms);
        form_fields = JSON.parse(form_fields);  


        /*Setting up the data*/
        var chk_create = 'checked="checked"';
        var chk_update = "";
        var chk_updateResp = "";

        //hiding of fields
        var hd_create = "";
        var hd_update = "display";
        var hd_updateRes = "display";

        //create fields
        if(data!=""){
            //for hiding fields(create or update)
            if(data['workflow-trigger-action']=="Create"){
                hd_create = "";
                hd_update = "display";
                hd_updateRes = "display";
            }else if(data['workflow-trigger-action']=="Update Response"){
                hd_updateRes = "";
                hd_create = "";
                hd_update = "display";
            }else{
                hd_create = "display";
                hd_update = ""
                hd_updateRes = "display";
            }
            //for trigger action(create or update)
            chk_create = setChecked("Create", data['workflow-trigger-action']);
            chk_update = setChecked("Update", data['workflow-trigger-action']);
            chk_updateResp = setChecked("Update Response", data['workflow-trigger-action']);

            //create fields

        }
        var ret = '<div class="trigger-container-fields trigger-container-fields_'+ctr+'" style="">';
            ret += '<div style="float: left;border: 1px solid #E2DCDC;height: auto;padding: 7px;width: 92%;margin-bottom:10px">';
                ret += '<div style="float: left;width:23%;">';
                    ret += '<div class="fields_below" style="width:98%;">';
                        ret += '<div class="label_below2">Action: <font color="red">*</font></div>';
                        ret += '<div class="input_position_below">';
                        ret += '<div style="font-size:11px"><label><input type="radio" name="workflow-trigger-action_'+ ctr +'" value="Create" '+ chk_create +' class="workflow-trigger-action-class"><span> Create Response</span></label></div>';
                        ret += '<div style="font-size:11px"><label><input type="radio" name="workflow-trigger-action_'+ ctr +'" value="Update Response" '+ chk_updateResp +' class="workflow-trigger-action-class"><span> Update Response</span></label></div>';
                        ret += '<div style="font-size:11px"><label><input type="radio" name="workflow-trigger-action_'+ ctr +'" value="Update" '+ chk_update +' class="workflow-trigger-action-class"><span> Update Field</span></label></div>';
                        ret += '</div>';
                    ret += '</div>';
                ret += '</div>';

                //FOR UPDATE TRIGGER
                ret += '<div class="forUpdateTrgger '+ hd_update +'">';
                    ret += '<div style="float:left;width:23%;">';
                        ret += '<div class="fields_below" style="width:98%;">';
                            ret += '<div class="label_below2">Field Filter: <font color="red">*</font></div>';
                            ret += '<div class="input_position_below">';
                                ret += '<select class="form-select workflow-trigger-fields-filter" id="" style="margin-top:0px">';
                                for (i in form_fields) {
                                    // console.log(form_fields)
                                    if(data!=""){
                                        ret += '<option '+ setSelected(form_fields[i], data['workflow-trigger-fields-filter']) +'>'+ form_fields[i] +'</option>';
                                    }else{
                                        ret += '<option>'+ form_fields[i] +'</option>';
                                    }
                                }
                                ret += '</select>';
                            ret += '</div>';
                        ret += '</div>';
                    ret += '</div>';
                    ret += '<div style="float:left;width:23%;">';
                        ret += '<div class="fields_below" style="width:98%;">';
                            ret += '<div class="label_below2">Field Update: <font color="red">*</font></div>';
                            ret += '<div class="input_position_below">';
                                ret += '<select class="form-select workflow-trigger-fields-update" id="" style="margin-top:0px">';
                                for (i in form_fields) {
                                    // console.log(form_fields)
                                    if(data!=""){
                                        ret += '<option '+ setSelected(form_fields[i], data['workflow-trigger-fields-update']) +'>'+ form_fields[i] +'</option>';
                                    }else{
                                        ret += '<option>'+ form_fields[i] +'</option>';
                                    }
                                }
                                ret += '</select>';
                            ret += '</div>';
                        ret += '</div>';
                    ret += '</div>';
                    ret += '<div style="float:left;width:23%;">';
                        ret += '<div class="fields_below" style="width:98%;">';
                            ret += '<div class="label_below2">Operator: <font color="red">*</font></div>';
                            ret += '<div class="input_position_below">';
                                ret += '<select class="form-select workflow-trigger-operator" id="" style="margin-top:0px">';
                                    if(data!=""){
                                        ret += '<option value="Addition" '+ setSelected("Addition", data['workflow-trigger-operator']) +'>Addition</option>'
                                        ret += '<option value="Subtraction" '+ setSelected("Subtraction", data['workflow-trigger-operator']) +'>Subtraction</option>'
                                        ret += '<option value="Multiplication" '+ setSelected("Multiplication", data['workflow-trigger-operator']) +'>Multiplication</option>'
                                        ret += '<option value="Division" '+ setSelected("Division", data['workflow-trigger-operator']) +'>Division</option>'
                                    }else{
                                        ret += '<option value="Addition">Addition</option>'
                                        ret += '<option value="Subtraction">Subtraction</option>'
                                        ret += '<option value="Multiplication">Multiplication</option>'
                                        ret += '<option value="Division">Division</option>'
                                    }
                                ret += '</select>';
                            ret += '</div>';
                        ret += '</div>';
                    ret += '</div>';
                ret += '</div>';
                //FOR CREATE TRIGGER
                ret += '<div class="forCreateTrgger '+ hd_create +'">';
                    ret += '<div style="float:left;width:32.5%;margin-right:10px">';
                        ret += '<div class="fields_below" id="forFormTrigger">';
                            ret += '<div class="label_below2">Form Trigger: <font color="red">*</font></div>';
                            ret += '<div class="input_position_below">';
                                ret += '<select class="form-select workflow-form-trigger" id="workflow-form-trigger" style="margin-top:0px">';
                                    ret += '<option value="0">--Select Form--</option>';
                                for (i in forms) {
                                    // console.log(form_fields)
                                    if(data!=""){
                                        ret += '<option value="'+ forms[i]['id'] +'" '+ setSelected(forms[i]['id'], data['workflow-form-trigger']) +'>'+ forms[i]['form_name'] +'</option>';
                                    }else{
                                        ret += '<option value="'+ forms[i]['id'] +'">'+ forms[i]['form_name'] +'</option>';
                                    }
                                }
                                ret += '</select>';
                                ret += '<img src="/images/loader/loading.gif" class="pull-left display replDisp processorLoad"/>';
                            ret += '</div>';
                        ret += '</div>';
                    ret += '</div>';
                    ret += '<div style="float:left;width:33%;margin-right:10px;height: 58px;">';
                        ret += '<div class="fields_below forUpdateResponse '+ hd_updateRes +'" id="">';
                            ret += '<div class="label_below2">Reference Field: <font color="red">*</font></div>';
                            ret += '<div class="input_position_below">';
                                ret += '<select class="form-select workflow-ref-field" id="workflow-ref-field" style="margin-top:0px">';
                                    for (i in form_fields) {
                                        // console.log(form_fields)
                                        if(data!=""){
                                            ret += '<option '+ setSelected(form_fields[i], data['workflow-ref-field']) +'>'+ form_fields[i] +'</option>';
                                        }else{
                                            ret += '<option>'+ form_fields[i] +'</option>';
                                        }
                                    }
                                ret += '</select>';
                                ret += '<img src="/images/loader/loading.gif" class="pull-left display replDisp processorLoad"/>';
                            ret += '</div>';
                        ret += '</div>';
                    ret += '</div>';
                    ret += '<div class="fields_formula" style="float: left;width: 100%;">';
                    if(data!=""){
                        var field_formula = data['workflow-field_formula'];
                        if(field_formula!=undefined){
                            for(var i in field_formula){
                                ret +=  this.fields_formula(ctr,field_formula[i],i);
                            }
                        }else{
                            ret +=  this.fields_formula(ctr,"",0);
                        }
                        
                    }else{
                        ret +=  this.fields_formula(ctr,"",0);
                    }
                    ret += '</div>';
                    
                ret += '</div>';
            ret += '</div>';    
            ret += '<div style="float:left;font-size: 15px;position: relative;">';
                ret += '<div style="float:left;width:100%;margin-left:5px;">';
                    ret += '<i class="addtrigger icon-plus-sign cursor"></i>';
                    if(ctr!=0){
                        ret += '<i class="minusTrigger icon-minus-sign cursor" style="margin-left:5px;"></i>';
                    }
                ret += '</div>';  
            ret += '</div>';    
        ret += '</div>';   
        return ret;
    },
    fields_formula : function(ctr,data,row_ctr){
        var fmula = ""
        if(data!=""){
            fmula = data['workflow-field-formula'];
        }
        var ret = '<div class="fields_formula_row" style="display:none;"><div style="float:left;width: 87%;margin-right:10px;border: 1px solid #E2DEDE;padding: 5px;margin-bottom:10px">';
                        ret += '<div class="fields_below" id="forReferenceField" style="width: 45%;float: left;margin-right: 10px;">';
                            ret += '<div class="label_below2">Field: <font color="red">*</font></div>';
                            ret += '<div class="input_position_below">';
                                ret += '<select class="form-select workflow-reference-fields-update" id="workflow-reference-fields-update_'+ctr+'_'+row_ctr+'" style="margin-top:0px">';
                                ret += '<option value="0">--Select Field--</option>';
                                ret += '</select>';
                                ret += '<img src="/images/loader/loading.gif" class="pull-left display replDisp processorLoad"/>';
                            ret += '</div>';
                        ret += '</div>';
                        ret += '<div style="float:left;width:45%;margin-right:10px">';
                            ret += '<div class="fields_below" id="forReferenceField">';
                                ret += '<div class="label_below2">Formula: <font color="red">*</font></div>';
                                ret += '<div class="input_position_below">';
                                    ret += '<textarea class="form-textarea workflow-reference-fields-formula" style="margin-top:0px;resize:none">'+ fmula +'</textarea>';
                                ret += '</div>';
                            ret += '</div>';
                        ret += '</div>';
                    ret += '</div>';    
                    ret += '<div style="float:left;width:7%;font-size: 15px;position: relative;">';
                        ret += '<div style="float:left;width:100%;margin-left:5px;">';
                            ret += '<i class="addFieldtrigger icon-plus-sign cursor"></i>';
                            if(row_ctr!=0){
                                ret += '<i class="minusFieldTrigger icon-minus-sign cursor" style="margin-left:5px;"></i>';
                            }
                        ret += '</div>';  
                    ret += '</div></div>';
        return ret;
    }
    
}

$(document).ready(function(){

    resizeForm($(".workflow_ws"), "600","workflow")
    
    //container
    var node_container = '.workspace';

    workflow_actions.setMembersFunction();

    
    //to make the workspace of workflow resizable
    $(".workflow_ws").resizable({
    handles:"s,e"
    })
    
    /* ORGCHART */
    //get and set nodes from database
    var workflow_lines = $("#workflow_lines").text();
    if (workflow_lines) {
        workflow_lines = JSON.parse(workflow_lines);
        var json_body = $("body").data();
        var json_linedata = {};
        
        for (var a=0; a<workflow_lines.length;a++) {
            var lines = JSON.parse(workflow_lines[a]);
            var json_title = lines['json_title'];
            if(lines['line-type']!="arrow"){
            //append line
            $(node_container).append('<span class="lines '+ lines['line-type'] +
                                        '" json_title="'+ json_title +
                                        '" line-class="'+ lines['line-class'] +
                                        '" parent="'+ lines['parent'] +'" child="'+ lines['child'] +
                                        '" style="top:'+ lines['top'] +'px;left:'+
                                        lines['left'] +'px;width:'+ lines['width'] +'px;height:'+
                                        lines['height'] +'px;background-color:'+
                                        lines['background-color'] +';"></span>');

            }else{
            //appendline
            $(node_container).append('<span class="lines arrow" json_title="'+ json_title +'" line-class="'+ lines['line-class'] +
                                             '" parent="'+ lines['parent'] +
                                             '" child="'+ lines['child'] +
                                             '" style="top:'+ lines['top'] +'px;left:'+ lines['left'] +'px;'+ lines['border'] +'"></span>');
            }
                json_linedata[''+ lines['line-class'] +'_'+lines['line-type']] = {};
                json_linedata[''+ lines['line-class'] +'_'+lines['line-type']] =  lines;
        }
        json_body['lines'] = json_linedata;
        $("body").data(json_body);
    
    }
    
    //get and set nodes from database
    var workflow_nodes = $("#workflow_nodes").text();
    if (workflow_nodes) {
        workflow_nodes = JSON.parse(workflow_nodes);
        var ctr = 1;
        $.each(workflow_nodes, function(key, value){
            var json_nodes = JSON.parse(value)
            var line_class = "";
            if(json_nodes['node_type']=="circle"){
                json_nodes['node_type'] = "circle2";
            }else if(json_nodes['node_type']=="box" ){
                if(json_nodes['type_rel']==2){
                    json_nodes['node_type'] = "processor";
                }else if(json_nodes['type_rel']==3){
                    json_nodes['node_type'] = "condition";
                }
            }
            nodeDesign(json_nodes);
            if(json_nodes['buttonStatus']){
                $.each(json_nodes['buttonStatus'], function(btnKey, btnValue){
                    line_class = json_nodes['buttonStatus'][''+ btnKey +'']['parent_id']+"_"+json_nodes['buttonStatus'][''+ btnKey +'']['child_id'];
                    customTextLine(line_class,btnKey);
                })
            }
            if(json_nodes['condition_return']){
                $.each(json_nodes['condition_return'], function(cdtnkey, cdtnValue){
                    line_class = json_nodes['condition_return'][''+ cdtnkey +'']['parent_id']+"_"+json_nodes['condition_return'][''+ cdtnkey +'']['child_id'];
                    customTextLine(line_class,cdtnkey);
                })
            }
            if(ctr==workflow_nodes.length){
                for(var i in workflow_nodes){
                    var json_nodes2 = JSON.parse(workflow_nodes[i]);
                    nodeId = json_nodes2['node_data_id'];
                    moveLines(nodeId,"");

                }
            }
            ctr++;
        })
        // for (var a=0; a<workflow_nodes.length;a++) {
     //        var json_nodes = JSON.parse(workflow_nodes[a])
        //     nodeDesign(json_nodes);
     //        if(json_nodes['buttonStatus']){
     //            var line_class = json_nodes['buttonStatus']
     //            console.log(line_class)
     //            //customTextLine(line_class,"Sample");
     //        }
        // }
    }
    //variables in nodes function
    
    var node_linecolor = '#424242';
    //initialize node functions on load
    node.mouseoverNode();
    node.mouseleaveNode();
    node.mousedown();
    node.activateNode();
    node.dragAlso();
    node.dropToNode('.node-drag',node_container,node_linecolor);
    node.dragNode(".outer-node",node_container,true,node_linecolor);
    node.resizeNode(node_container,node_linecolor);
    node.resizeStartNode(node_container,node_linecolor);
    //Node Settings
    nodeSettings.minimizeNode(node_linecolor);
    nodeSettings.maximizeNode(node_linecolor);
    //Line Trigger Drag
    // Control Save Workspace
    // Main Function of save is on the formbuilder.js
    /*-----------------------------------------------------*/
    
    
/*
 * Add node to the workspace Workflow Chart
 * ('Start Node','End Node','Process Node','Conditional')
 * 
 */
    
    $(".process_node").node({
    event       : 'click',
    container   : '.workspace',
    startCount  : 1,
    type        : "processor",
    defaultText : "Processor",
    nodeColor   : "#424242",
    lineColor   : node_linecolor,
    type_rel    : "2",
    enableRuler : true,
        onDrop          : function(parent,child,addline){
            //get parent id
            var node_data_id = $(parent).closest(".outer-node").attr("id")
            //get child id
            var child_id = $(child).closest(".outer-node").attr("id");
            //modal type
            var object_type = "workflow_chart_buttons";
            
            //set modal
            jDialog(object_properties_node(object_type,node_data_id,child_id), "","500", "", "", function(){});
            
            
            //set color picker for line
            $("#wokflow_button-line-color").spectrum({
                        color: "424242"
            });  
            
            //end of the function
            
            //click to save json to node
            workflow_actions.save_node_settings(function(line_color,json_title){
                        addline(line_color,json_title);
            })
        },
        settings_property : "workflow_chart-processor"
    });
    
    //START NODE
    $(".start_node").node({
    event       : 'click',
    container   : '.workspace',
    startCount  : 1,
    type        : "circle2",
    defaultText : "Start",
    nodeColor   : "#424242",
    lineColor   : node_linecolor,
    type_rel    : "1",
    enableRuler : false,
    height  : "80px",
    width   : "90px",
    maxCount    : 1,
    onDrop      : function(parent,child,addline){
            //get parent id
            var node_data_id = $(parent).closest(".outer-node").attr("id")
            //get child id
            var child_id = $(child).closest(".outer-node").attr("id");
            //modal type
            var object_type = "workflow_chart_buttons";
            
            //set modal
            jDialog(object_properties_node(object_type,node_data_id,child_id), "","500", "", "", function(){});
            
            //set color picker for line
            $("#wokflow_button-line-color").spectrum({
                        color: "424242"
            });  
            
            //end of the function
            
                            
            //click to save json to node
            workflow_actions.save_node_settings(function(line_color,json_title){
                        addline(line_color,json_title);
            })
    },
    settings_property : "workflow_chart-start",
    drop            : false
    });
    
    //CONDITION NODE
    
    $(".conditional_node").node({
    event       : 'click',
    container   : '.workspace',
    startCount  : 1,
    type        : "condition",
    defaultText : "Condition",
    nodeColor   : "#424242",
    type_rel    : "3",
    lineColor   : node_linecolor,
        enableRuler : false,
        onDrop            : function(parent,child,addline){
            //get parent id
            var node_data_id = $(parent).closest(".outer-node").attr("id")
            //get child id
            var child_id = $(child).closest(".outer-node").attr("id");
            //modal type
            var object_type = "workflow_chart_condition-line";
            //set modal
            jDialog(object_properties_node(object_type,node_data_id,child_id), "","500", "", "", function(){});
            
            //set color picker for line
            $("#wokflow_condition-line-color").spectrum({
                        color: "424242"
            });  
            
            //end of the function
            //click to save json to node
            workflow_actions.save_node_settings(function(line_color,json_title){
                        addline(line_color,json_title);
            })
        },
        settings_property : "workflow_chart-condition"
    });
    
    //END NODE
    
    $(".end_node").node({
    event       : 'click',
    container   : '.workspace',
    startCount  : 1,
    type        : "circle2",
    defaultText : "End",
    nodeColor   : "#424242",
    type_rel    : "4",
    lineColor   : node_linecolor,
    height  : "80px",
    width   : "90px",
    maxCount    : 1,
        settings_property : "workflow_chart-end",
        enableRuler : false,
        hasDrag         : false
    });
    
    //event change of processor type
    $("body").on("change","#workflow-processor-type, .workflow-processor-type",function(){
          var value = $(this).val();
      $("#workflow-processor, #workflow-processor").hide();
      $(".processorLoad").show();
          getprocessor(value,0);
    })
    // OOP JS Functions Call
            /* Main Workspace */
                workspace_functions.view_save(".save_workspace");
            /* Main Workflow */
                workflow_actions.save_form_workspace(".save_form_workspace");/* Main Workflow */
                
                /* Save Settings */
                //workflow_actions.save_node_settings();/* Main Workflow */
    //GET PROCESSOR TYPE
    

    //Email
    $("body").on("click",".node-email",function(){

        var node_id = $(this).closest(".outer-node").attr("id");
        workflow_actions.save_node_mail(node_id);

        RequestPivacy.bindOnClickCheckBox();
        $('.content-dialog-scroll').perfectScrollbar();
        $('.content-dialog-scroll-container').perfectScrollbar();
        
        $(".ps-scrollbar-x").hide();

    })
    $("body").on("click",".node-field-trigger",function(){
        var node_id = $(this).closest(".outer-node").attr("id");
        workflow_actions.field_trigger_settings(node_id);
    })
    
    $("body").on("click",".formUser",function(){
        var showPanel = $(this).attr("rel");
        var container = $(this).closest(".container-formUser");
        container.find("."+showPanel).slideToggle(function(){
            var displ = $(this).css("display");
            if(displ=="block" || displ=="inline-block" ){
                $(this).css("display","inline-block");
                $(this).closest(".container-formUser").find("label.icon").removeClass("icon-plus").addClass("icon-minus")
            }else{
                $(this).closest(".container-formUser").find("label.icon").removeClass("icon-minus").addClass("icon-plus")
            }
            $('#content-dialog-scroll').perfectScrollbar('update');
            //$('#content-dialog-scroll').perfectScrollbar();

        });
        
    })  

    $('body').on('dblclick',".outer-node", function (e) {
        var pathname = window.location.pathname;
        if(!$(this).hasClass('ui-draggable') && pathname=="/workspace"){
            return;
        }
        // $(".node-setting").click();
        var node_data_id = $(this).attr("data-node-id");
        var object_type = $(this).find(".node-setting").attr("data-object-type");
        setNodesData(node_data_id,object_type)
    }) 
    //NODE SETTINGS
    $('body').on('click',".node-setting", function (e) {
        var node_data_id = $(this).closest(".outer-node").attr("data-node-id");
        var object_type = $(this).attr("data-object-type");
        setNodesData(node_data_id,object_type)

    });

    if ($(".workspace.workflow_ws").find(".outer-node").length >= 1) {
        if (checkFormMinWidth("workflow") != null) {
            $(".workspace.workflow_ws").resizable("option", "minWidth", checkFormMinWidth("workflow"));
        }
        if (checkFormMinHeight("workflow") != null) {
            $(".workspace.workflow_ws").resizable("option", "minHeight", checkFormMinHeight("workflow"));
        }
        $(".workspace.workflow_ws").css({
            "height": $("#workflow_height").text()+"px",
            "width": $("#workflow_width").text()+"px",

        });
        $(".leftPointerRuler-container").css({
            "height": $("#workflow_height").text()+"px",
        })
    }


    //multi
    workflow_actions.field_trigger_custom();  


    $("body").on("click",".clear_all_nodes",function(){
        var nodes = $(".outer-node").length;
        if(nodes==0){
            return;
        }
        con = "Are you sure you want to remove all nodes??";
        jConfirm(con, 'Confirmation Dialog','', '', '', function(r){
            if(r==true){
                removeAllNodes();
            }
        });
    })
    var pathname = window.location.pathname;
    if(pathname!="/workflow"){
        return;
    }
    var ws_width = $(".workflow_ws").outerWidth();
    var ws_height = $(".workflow_ws").outerHeight();
    $(".form_size_width").val(ws_width);
    $(".form_size_height").val(ws_height)
})
function setNodesData(node_data_id,object_type){
    ui.block();
    var json_nodes = $("body").data();
        var json_nodes_var = json_nodes['nodes'];
    // Remove other open popover
    //$('.object_properties').not(this).popover('hide');
    
    var width = "500";
    if(object_type=="workflow_chart-processor" || object_type=="workflow_chart-start"){
        width = "650";
    }else if(object_type=="organizational_chart"){
        width = "650";
    }
    jDialog(object_properties_node(object_type,node_data_id,""), "",width, "", "", function(){});
    
    //field enabled
    CheckProperties.setCheckAllChecked(".fieldEnabled",".f_enabled",".checkAllFields");
    CheckProperties.bindOnClickCheckBox(".fieldEnabled",".f_enabled",".checkAllFields");
    //field required
    CheckProperties.setCheckAllChecked(".fieldRequired",".f_required",".checkAllFields");
    CheckProperties.bindOnClickCheckBox(".fieldRequired",".f_required",".checkAllFields");
    //field hidden
    CheckProperties.setCheckAllChecked(".fieldHiddenValue",".f_hidden",".checkAllFields");
    CheckProperties.bindOnClickCheckBox(".fieldHiddenValue",".f_hidden",".checkAllFields");


    limitText(".limit-text-wf",25); // set limit of text in the fields  
    if (object_type=="organizational_chart") {
        getUser(node_data_id,"",0,function(){
            $('#content-dialog-scroll').perfectScrollbar();
            limitText(".limit-text-wf",19); // set limit of text in the name  
            $(".tip").tooltip(); 
            ui.unblock();
            workflow_actions.setMembers();
            if($(".userLevel").val()!=2){
                $(".settings-to-json").remove();
                $("#orgchart-dept-name, .member_user, .asst_head_user, .head_user").attr("disabled","disabled");
                $(".chngColor[data-properties-type='nodeColor']").spectrum({
                    disabled: true,
                });
                $(".cancel_dialog").val("Close")
            }
            ui.unblock();
        });
    }else if (object_type=="workflow_chart-processor" || object_type=="workflow_chart-start" || object_type=="workflow_chart-end" || object_type=="workflow_chart-condition" ) {
        //getFlds();
            $('#content-dialog-scroll').perfectScrollbar();
        ui.unblock();
    }
    
    
    $(".tip").tooltip(); 
    //for processor
    var workflow_processor_type = if_undefinded(json_nodes_var[''+ node_data_id +'']['processorType'],"");
    var workflow_processor = if_undefinded(json_nodes_var[''+ node_data_id +'']['processor'],"");
    getprocessor(workflow_processor_type,workflow_processor);


    //hide scroll x
    
    $(".ps-scrollbar-x").hide();
    
    var node_color = if_undefinded(json_nodes_var[''+ node_data_id +'']['node_color'],"#424242");
    $(".chngColor[data-properties-type='nodeColor']").spectrum({
        color: node_color
    });
    //enable save json properties
    workflow_actions.save_node_settings(null);


    
}
function getprocessor(value,selected) {
   var form_id = $("#form_id").val();;
   $.post("/ajax/workflow",{action:"getProcessor",value:value,selected:selected,form_id:form_id},function(data){
        if(data=="0"){
            showNotification({
                 message: "No Orgchart activated",
                 type: "error",
                 autoClose: true,
                 duration: 3
            });
        }else{
            $("#workflow-processor, .workflow-processor").html(data);
        }
        $(".processorLoad").hide();
        $("#workflow-processor, .workflow-processor").show();
   })
}

//for multi
function getFormFields(ele,form_id,selectedVal,callback){
    if(form_id==0){
        ele.closest(".trigger-container-fields").find(".workflow-reference-fields-update").html("<option value='0'>--Select Field--</option>");
        return;
    }
    if(selectedVal=="null"){
        ele.closest(".trigger-container-fields").find(".workflow-reference-fields-update").last().next().removeClass("display");
        ele.closest(".trigger-container-fields").find(".workflow-reference-fields-update").last().addClass("display")
    }else{
        ele.closest(".trigger-container-fields").find(".workflow-reference-fields-update").next().removeClass("display");
        ele.closest(".trigger-container-fields").find(".workflow-reference-fields-update").addClass("display")
    }
    $.post("/ajax/workflow",{action:"getFormFields",form_id:form_id},function(data){
        data = JSON.parse(data)
        var ret = "";
        for(var i in data){
            ret += "<option "+ setSelected(data[i], selectedVal) +">"+ data[i] +"</option>";
        }
        if(selectedVal=="null"){
            ele.closest(".trigger-container-fields").find(".workflow-reference-fields-update").last().html(ret);
            ele.closest(".trigger-container-fields").find(".workflow-reference-fields-update").last().next().addClass("display");
            ele.closest(".trigger-container-fields").find(".workflow-reference-fields-update").last().removeClass("display")
        }else{
            ele.closest(".trigger-container-fields").find(".workflow-reference-fields-update").html(ret);
            ele.closest(".trigger-container-fields").find(".workflow-reference-fields-update").next().addClass("display");
            ele.closest(".trigger-container-fields").find(".workflow-reference-fields-update").removeClass("display")
        }
        if(typeof callback=="function"){
            callback(1);
        }
    })
}
function getFlds() {
 //    var pathname = window.location;
 //    var formID = getParametersName("form_id",pathname);
    
 //    $.post("/ajax/getFormProperties",{action:"getFlds",formID:formID},function(result){
    // var flds = JSON.parse(result);
    // var ret = "";
    //     for (i in flds) {
    //      ret += '<input type="checkbox" name="field_' + flds[i].fieldName + '" value="' + flds[i].fieldName + '" /> ' + flds[i].fieldName + '<br />';
            
    //     }    
    // $(".fieldEnabled").append(ret);
    // $(".fieldHiddenValue").append(ret);
    // //
    
 //    });
}
function array_store(classToEach,type){
    var array_var = new Array();
    if(type=="checkbox"){
        $(classToEach).each(function(){
            if($(this).prop("checked")){
                array_var.push($(this).val())
            }
        }); 
    }
    return array_var;
}
function json_haselement(json){
    var ctr = 0;
    var ret = false;
    for(var i in json){
        ctr++;
    }
    if(ctr>0){
        ret =  true;
    }
    return ret;
}
function triggerHtml(json){
    var ret = "";
    var disp = "";
    var form_fields = $(".form_fields").val();
    var forms = $(".company_forms").text();
    var label = [];
    var margin = "";
    var cssDisplayCreate = "";var cssDisplayCreate = "";
    form_fields = JSON.parse(form_fields);
    forms = JSON.parse(forms);
    
    for(var i in json){
        disp = "";
        label = ["","","","","",""]
        margin = "margin-top:10px";
        if(i==0){
            disp = "display";
            label = ['Action: <font color="red">*</font>','Field Filter: <font color="red">*</font>','Field Update: <font color="red">*</font>','Operator: <font color="red">*</font>','Form Trigger: <font color="red">*</font>','Refence Field: <font color="red">*</font>'];
            margin = "margin-top:30px";
        }
        if(json[i]['workflow-trigger-action']=="Create"){
            cssDisplayCreate = "";
            cssDisplayUpdate = "display replDisp";
        }else{
            cssDisplayCreate = "display replDisp";
            cssDisplayUpdate = "";
        }
        ret += '<div class="trigger-container-fields" style="">';
        ret += '<div style="float: left;width:23%;">';
            ret += '<div class="fields_below" style="width:98%;">';
                ret += '<div class="label_below2">'+ label[0] +'</div>';
                ret += '<div class="input_position_below">';
                ret += '<div style="font-size:11px"><label><input type="radio" '+ setChecked("Update", json[i]['workflow-trigger-action']) +' name="workflow-trigger-action_'+ i +'" value="Update" checked="checked" class="workflow-trigger-action-class"><span> Update Field</span></label></div>';
                ret += '<div style="font-size:11px"><label><input type="radio" '+ setChecked("Create", json[i]['workflow-trigger-action']) +' name="workflow-trigger-action_'+ i +'" value="Create" class="workflow-trigger-action-class"><span> Create Request</span></label></div>';
                ret += '</div>';
            ret += '</div>';
        ret += '</div>';

        //FOR UPDATE TRIGGER
        ret += '<div class="forUpdateTrgger '+ cssDisplayUpdate +'">';
            ret += '<div style="float:left;width:23%;">';
                ret += '<div class="fields_below" style="width:98%;">';
                    ret += '<div class="label_below2">'+ label[1] +'</div>';
                    ret += '<div class="input_position_below">';
                        ret += '<select class="form-select workflow-trigger-fields-filter" id="" style="margin-top:0px">';
                        for (var j in form_fields) {
                            // console.log(form_fields)
                            ret += '<option '+ setSelected(form_fields[j], json[i]['workflow-trigger-fields-filter']) +'>'+ form_fields[j] +'</option>';
                        }
                        ret += '</select>';
                    ret += '</div>';
                ret += '</div>';
            ret += '</div>';
            ret += '<div style="float:left;width:23%;">';
                ret += '<div class="fields_below" style="width:98%;">';
                    ret += '<div class="label_below2">'+ label[2] +'</div>';
                    ret += '<div class="input_position_below">';
                        ret += '<select class="form-select workflow-trigger-fields-update" id="" style="margin-top:0px">';
                        for (var j in form_fields) {
                            // console.log(form_fields)
                            ret += '<option '+ setSelected(form_fields[j], json[i]['workflow-trigger-fields-update']) +'>'+ form_fields[j] +'</option>';
                        }
                        ret += '</select>';
                    ret += '</div>';
                ret += '</div>';
            ret += '</div>';
            ret += '<div style="float:left;width:23%;">';
                ret += '<div class="fields_below" style="width:98%;">';
                    ret += '<div class="label_below2">'+ label[3] +'</div>';
                    ret += '<div class="input_position_below">';
                        ret += '<select class="form-select workflow-trigger-operator" id="" style="margin-top:0px">';
                            ret += '<option value="Addition" '+ setSelected("Addition", json[i]['workflow-trigger-operator']) +'>Addition</option>'
                            ret += '<option value="Subtraction" '+ setSelected("Subtraction", json[i]['workflow-trigger-operator']) +'>Subtraction</option>'
                            ret += '<option value="Multiplication" '+ setSelected("Multiplication", json[i]['workflow-trigger-operator']) +'>Multiplication</option>'
                            ret += '<option value="Division" '+ setSelected("Division", json[i]['workflow-trigger-operator']) +'>Division</option>'
                        ret += '</select>';
                    ret += '</div>';
                ret += '</div>';
            ret += '</div>';
        ret += '</div>';
        //FOR CREATE TRIGGER
        ret += '<div class="forCreateTrgger '+ cssDisplayCreate +'">';
            ret += '<div style="float:left;width:32.5%;margin-right:10px">';
                 ret += '<div class="fields_below" id="forFormTrigger">';
                    ret += '<div class="label_below2">'+ label[4] +'</div>';
                    ret += '<div class="input_position_below">';
                        ret += '<select class="form-select workflow-form-trigger" id="workflow-form-trigger_'+ i +'" style="margin-top:0px">';
                            ret += '<option value="0">--Select Form--</option>';
                        for (var j in forms) {
                            // console.log(form_fields)
                            ret += '<option '+ setSelected(forms[j]['id'], json[i]['workflow-form-trigger']) +' value="'+ forms[j]['id'] +'">'+ forms[j]['form_name'] +'</option>';
                        }
                        ret += '</select>';
                        ret += '<img src="/images/loader/loading.gif" class="pull-left display replDisp processorLoad"/>';
                    ret += '</div>';
                ret += '</div>';
            ret += '</div>';
            ret += '<div style="float:left;width:33%;margin-right:10px">';
                ret += '<div class="fields_below" id="forReferenceField">';
                    ret += '<div class="label_below2">'+ label[5] +'</div>';
                    ret += '<div class="input_position_below">';
                        ret += '<select class="form-select workflow-reference-fields-update" id="workflow-reference-fields-update" style="margin-top:0px">';
                        ret += '<option value="0">--Select Field--</option>';
                        ret += '</select>';
                        ret += '<img src="/images/loader/loading.gif" class="pull-left display replDisp processorLoad"/>';
                    ret += '</div>';
                ret += '</div>';
            ret += '</div>';
        ret += '</div>';
        ret += '<div style="float:left;width:8%;font-size: 15px;position: relative;">';
            ret += '<div style="float:left;width:100%;margin-left:5px;'+ margin +'">';
                ret += '<i class="addtrigger icon-plus-sign cursor"></i>';
                ret += '<i class="minusTrigger icon-minus-sign cursor '+ disp +'" style="margin-left:5px;"></i>';
            ret += '</div>';  
        ret += '</div>';    
    ret += '</div>';    
    }
    return ret;
}
function removeAllNodes(){
    var json_nodes = $("body").data();
    delete json_nodes['nodes'];
    delete json_nodes['lines'];

    $(".outer-node").remove();
    $(".lines").remove();

}
function converBreakLineTextbox(ele){
    value = $(ele).val();
    value = converBreakLine(value);
    $(ele).val(value);
}
function converBreakLine(value){
    return value.replace(/<br\s?\/>/g,"\n");
}